﻿////////////////////////////////////////////////////
//
// Copyright (c) 2010, Cristian Daini
// All rights reserved.
// 
// http://laharsubsample.codeplex.com/
//
////////////////////////////////////////////////////

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;

namespace Chat
{
    public class VerifyConnection
    {
        SynchronizationContext context;
        WebRequest request;
        Action onSuccess;
        Action<Exception> onError;


        public static void IsConnectionAvailable(string Address, Action onSuccess, Action<Exception> onError)
        {
            WebRequest request = WebRequest.Create(Address);
            IAsyncResult response = request.BeginGetResponse(IsConnectionAvailableResponse,
                new VerifyConnection
                {
                    context = SynchronizationContext.Current,
                    request = request,
                    onSuccess = onSuccess,
                    onError = onError
                });
        }


        static void IsConnectionAvailableResponse(IAsyncResult result)
        {
            VerifyConnection obj = (VerifyConnection)result.AsyncState;
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)obj.request.EndGetResponse(result);
                obj.context.Post(
                    delegate(object state)
                    {
                        obj.onSuccess();
                    },
                    null);
            }
            catch (Exception ex)
            {
                obj.context.Post(
                    delegate(object state)
                    {
                        obj.onError(ex);
                    },
                    null);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }

        ////////////////////////////////////////////////////

        public static void IsFileAccessible(string Address, Action onSuccess, Action<Exception> onError)
        {
            WebClient wclient = new WebClient();
            wclient.DownloadStringCompleted += delegate(object sender2, DownloadStringCompletedEventArgs args)
            {
                if (args.Error == null)
                {
                    onSuccess();
                }
                else
                {
                    onError(args.Error);
                }
            };
            wclient.DownloadStringAsync(new Uri(Address));
        }

    }
}
